package pers.qianyu.module.image.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pers.qianyu.module.core.domain.image.entity.ImagePO;
import pers.qianyu.module.core.util.TokenizerUtil;
import pers.qianyu.module.core.util.TrieTreeUtil;
import pers.qianyu.module.image.dao.ImageDao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 项目启动的时候，将数据库中keywords添加到前缀树中
 *
 * @author mizzle rain
 * @date 2021-03-17 11:47
 */
@Component
public class KeywordsToTrieTreeTask {
    @Autowired
    private ImageDao imageDao;

    @Scheduled(cron = "0 * * * * ?")
    public void execute() {
        System.out.println("KeywordsToTrieTreeTask.execute");
        final int limit = 500;
        new Thread(() -> {
            int pageNo = 1;
            long total = limit;
            Set<String> titles = new HashSet<>();
            while ((long) pageNo * limit <= total) {
                Page<ImagePO> page = new Page<>(pageNo, limit);
                QueryWrapper<ImagePO> wrapper = new QueryWrapper<>();
                wrapper.select("title");
                Page<ImagePO> imagePOPage = imageDao.selectPage(page, wrapper);
                List<ImagePO> records = imagePOPage.getRecords();
                total = page.getTotal();
                for (ImagePO record : records) {
                    Set<String> set = TokenizerUtil.splitKeyWords(record.getTitle());
                    titles.addAll(set);
                }
                pageNo++;
            }
            titles.forEach(TrieTreeUtil::insert);
        }).start();
    }
}
